/*
 * C/C++ Lessons Program
 * 
 * Copyright (c) 2012 Ken Zhang (cpp.china@gmail.com)
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this program; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA  02111-1307  USA
 *
 */


#include <unistd.h>
#include <stdio.h>
#include <stdarg.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

void printf2(const char * fmt, ...)
{
	static int index = 0;
	char buffer[128];
	int n = 0;

	n = sprintf(buffer, "%2d> ", ++index);

	va_list args;
	va_start(args, fmt);
	n += vsnprintf(buffer + n, sizeof(buffer)-1, fmt, args);
	va_end(args);
	
	if (n > 0) {
		write(STDOUT_FILENO, buffer, n);
	}
}

int main()
{
	// copy stdout to a new fd 
	printf2("Backup the FD of stdout.\n");
	int fd_stdout = dup(STDOUT_FILENO);
	int i;

	printf2("Now output 10 message.\n");

	for (i = 0; i < 5; i++) {
		printf2("Message %d\n", i);
	}

	printf2("Create a new file log.txt\n");
	int fd_log = open("log.txt", O_CREAT | O_TRUNC | O_WRONLY);
	if (fd_log < 0) {
		perror("Failed to create log.txt");
		return -1;
	}

	printf2("Call dup2 to copy the FD of log.txt to stdout.\n");
	dup2(fd_log, STDOUT_FILENO);

	printf2("Now continue output other messages...\n\n");
	for (i = 5; i < 10; i++) {
		printf2("Message %d\n", i);
	}

	printf2("Now restore stdout.\n");
	dup2(fd_stdout, STDOUT_FILENO);

	printf2("Total 10 messages, only 5 messages shown, check other message in log.txt.\n");

	close(fd_log);
	return 0;
}

